package com.android.allwinner.newaw360;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.Toast;

import com.android.allwinner.aw360.AW360API;
import com.android.allwinner.aw360.BirdViewListener;
import com.android.allwinner.aw360.CarPosition;
import com.android.allwinner.newaw360.common.APPConfig;
import com.android.allwinner.newaw360.media.AW360MediaManager;
import com.android.allwinner.newaw360.media.AW360MediaService;
import com.android.allwinner.newaw360.utils.AW360SharePreferenceUtil;
import com.android.allwinner.newaw360.utils.DisplayUtil;
import com.android.allwinner.newaw360.utils.FileUtils;
import com.android.allwinner.newaw360.utils.LogUtil;
import com.android.allwinner.newaw360.view.DisplaySetDialog;
import com.android.allwinner.newaw360.view.OnPasswordInputFinish;
import com.android.allwinner.newaw360.view.PasswordView;
import com.xinzhihui.mydvr.FileUtil;

public class BirdViewActivity extends AppCompatActivity implements View.OnClickListener, View.OnFocusChangeListener, BirdViewListener {
    private static final String TAG = BirdViewActivity.class.getSimpleName();
    private static final int PREVIEW_DIRCETION_ALL = 0;
    private static final int PREVIEW_DIRCETION_FRONT = 1;
    private static final int PREVIEW_DIRCETION_BEHIND = 2;
    private static final int PREVIEW_DIRCETION_LEFT = 3;
    private static final int PREVIEW_DIRCETION_RIGHT = 4;
    private static final int RED_POINT_VISIBLE = 1000;

    private Chronometer mClock;
    private ImageView red_Point;
    private int red_Point_Flag = 1;
    private SurfaceHolder mSurfaceHolder;
    private SurfaceView mSurfaceView;
    private ImageButton mModeView;
    private ImageButton mFrontView;
    private ImageButton mRearView;
    private ImageButton mLeftView;
    private ImageButton mRightView;
    private ImageButton mFilesView;
    private ImageButton mSetView;
    private ImageButton mRecordView;
    private Spinner mSensorSpinner;
    private Spinner mLensSpinner;

    private ConstraintLayout mMainLayout;
    /**
     * up
     * 条件缩放和位置
     */
    private LinearLayout mUpLayout;
    /**
     * left
     */
    private LinearLayout mControllerLayout;
    /**
     * right
     */
    private LinearLayout mControllerLayout2;
    private GridLayout mCalibrateLayout;
    private LinearLayout mCalibrateLayout2;
    private ImageView mCarView;
    private Button mSaveButton;
    private Button mCalibrateButton;
    private EditText mCarWidthView;
    private EditText mCarHeightView;
    private EditText mCarOffsetView;
    private PasswordView mPasswordView;

    private Switch mMirrorSwitch;
    private Button mExportButton;
    private Button mImportButton;


    private float mPreviewRate = -1f;

    private boolean isBirdView = true;//是否为鸟瞰模式
    private boolean isCalibrate = false;//是否为校正模式
    private boolean isActivate = true;//是否激活
    private int mPreviewDirection = -1;

    private ProgressDialog mProgressDialog;
    private AlertDialog mAlertDialog;

    long[] mHits = new long[2];

    private boolean fullscreen = true;//全屏显示
    /**
     * 应用退出时才会使用
     */
    private boolean isFirstPreview;

    private Handler mRedPointHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == RED_POINT_VISIBLE){
                if (red_Point_Flag == 0){
                    red_Point.setVisibility(View.VISIBLE);
                    red_Point_Flag = 1;
                }else {
                    red_Point.setVisibility(View.INVISIBLE);
                    red_Point_Flag = 0;
                }
                mRedPointHandler.sendEmptyMessageDelayed(RED_POINT_VISIBLE,500);
            }
        }
    };

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case AW360MediaService.MESSAGE_NO_SDCARD:
                    Toast.makeText(getApplicationContext(), R.string.SDCard_warning,
                            Toast.LENGTH_SHORT).show();
                    break;
                case AW360MediaService.MESSAGE_VIDEO_PATH_UNUSE:
                    Toast.makeText(getApplicationContext(), R.string.storageSpace_warning,
                            Toast.LENGTH_SHORT).show();
                case AW360MediaService.MESSAGE_NEXT_SAVE_FILE:
                    mClock.setBase(SystemClock.elapsedRealtime());
                case AW360MediaManager.MESSAGE_SERVICE_UNBIND:

                    break;
                case AW360MediaService.MESSAGE_START_RECORDER:
                    mClock.setBase(SystemClock.elapsedRealtime());
                    changeStatus(View.VISIBLE,R.mipmap.record_stop);
                    red_Point_Flag = 0;
                    break;
                case AW360MediaService.MESSAGE_STOP_RECORDER:
                    changeStatus(View.INVISIBLE,R.mipmap.record_start);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogUtil.i(TAG, "onCreate");
        setContentView(R.layout.activity_bird_view);

        isFirstPreview = true;
        if (fullscreen) {
            ConstraintLayout mContentView = (ConstraintLayout) findViewById(R.id.main_cl);
            mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
        }
        red_Point = (ImageView)findViewById(R.id.red_Point);
        red_Point.setVisibility(View.INVISIBLE);
        mClock = (Chronometer)findViewById(R.id.mClock);
        mClock.setVisibility(View.INVISIBLE);
    }

    @Override
    public void onBackPressed() {

    }

    private void initView() {
        AW360SharePreferenceUtil.init(this);
        mModeView = (ImageButton) findViewById(R.id.preview_model_ib);
        mFrontView = (ImageButton) findViewById(R.id.preview_front_ib);
        mRearView = (ImageButton) findViewById(R.id.preview_behind_ib);
        mLeftView = (ImageButton) findViewById(R.id.preview_left_ib);
        mRightView = (ImageButton) findViewById(R.id.preview_right_ib);
        mRecordView = (ImageButton) findViewById(R.id.start_record_ib);
        mSetView = (ImageButton) findViewById(R.id.set_ib);
        mFilesView = (ImageButton) findViewById(R.id.files_ib);
        mMainLayout = (ConstraintLayout) findViewById(R.id.main_cl);
        mControllerLayout = (LinearLayout) findViewById(R.id.controller_ll);
        mControllerLayout2 = (LinearLayout) findViewById(R.id.controller2_ll);
        mCalibrateLayout = (GridLayout) findViewById(R.id.calibrate_gl);
        mCalibrateLayout2 = (LinearLayout) findViewById(R.id.calibrate_ll);
        mSaveButton = (Button) findViewById(R.id.save_b);
        mCalibrateButton = (Button) findViewById(R.id.calibrate_b);
        mCarHeightView = (EditText) findViewById(R.id.car_height_et);
        mCarWidthView = (EditText) findViewById(R.id.car_width_et);
        mCarOffsetView = (EditText) findViewById(R.id.car_offset_et);
        mMirrorSwitch = (Switch) findViewById(R.id.mirror_s);
        mImportButton = (Button) findViewById(R.id.import_b);
        mExportButton = (Button) findViewById(R.id.export_b);
        mPasswordView = (PasswordView) findViewById(R.id.passwordView);
        mPasswordView.setVisibility(View.GONE);
        mPasswordView.setOnFinishInput(new OnPasswordInputFinish() {
            @Override
            public void inputFinish() {
                if ("123456".equals(mPasswordView.getStrPassword())) {
                    mPasswordView.setVisibility(View.GONE);
                    toCalibrateMode();
                    mPasswordView.clear();
                }
            }
        });

        mCarWidthView.setText("" + AW360API.getInstance().getCarWidth());
        mCarHeightView.setText("" + AW360API.getInstance().getCarHeight());
        mCarOffsetView.setText("" + AW360API.getInstance().getCarSideOffset());


        mCarWidthView.setOnFocusChangeListener(this);
        mCarHeightView.setOnFocusChangeListener(this);
        mCarOffsetView.setOnFocusChangeListener(this);
        mSaveButton.setOnClickListener(this);
        mCalibrateButton.setOnClickListener(this);
        mFilesView.setOnClickListener(this);
        mSetView.setOnClickListener(this);

        mModeView.setOnClickListener(this);
        mFrontView.setOnClickListener(this);
        mRearView.setOnClickListener(this);
        mLeftView.setOnClickListener(this);
        mRightView.setOnClickListener(this);
        mRecordView.setOnClickListener(this);
        mExportButton.setOnClickListener(this);
        mImportButton.setOnClickListener(this);
        mSensorSpinner = (Spinner) findViewById(R.id.sensor_spinner);
//        final ArrayAdapter<String> sensorAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.sensor_types));
        mSensorSpinner.setSelection(AW360API.getInstance().getCameraSensorType());
//        mSensorSpinner.setAdapter(sensorAdapter);
        mLensSpinner = (Spinner) findViewById(R.id.lens_spinner);
//        final ArrayAdapter<String> lensAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.lens_types));
//        mLensSpinner.setAdapter(lensAdapter);
        mLensSpinner.setSelection(AW360API.getInstance().getCameraLensType());
        mSensorSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String[] sensors = getResources().getStringArray(R.array.sensor_types);
                Toast.makeText(BirdViewActivity.this, sensors[position], Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        mLensSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String[] lens = getResources().getStringArray(R.array.lens_types);
                Toast.makeText(BirdViewActivity.this, lens[position], Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        mUpLayout = (LinearLayout) findViewById(R.id.up_controller_ll);
        findViewById(R.id.zoom_in_ib).setOnClickListener(this);
        findViewById(R.id.zoom_out_ib).setOnClickListener(this);
        findViewById(R.id.up_ib).setOnClickListener(this);
        findViewById(R.id.down_ib).setOnClickListener(this);
        findViewById(R.id.right_ib).setOnClickListener(this);
        findViewById(R.id.left_ib).setOnClickListener(this);
        findViewById(R.id.exchange_ib).setOnClickListener(this);

        findViewById(R.id.add_range_ib).setOnClickListener(this);
        findViewById(R.id.sub_range_ib).setOnClickListener(this);

        findViewById(R.id.exit_b).setOnClickListener(this);


    }

    private void initSurfaceView() {
        mSurfaceView = (SurfaceView) findViewById(R.id.surfaceView);
        mSurfaceView.setOnClickListener(this);
        mSurfaceHolder = mSurfaceView.getHolder();
        mSurfaceHolder.setFormat(PixelFormat.TRANSPARENT);//translucent半透明 transparent透明
        mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        initViewParams();
        mSurfaceHolder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                AW360MediaManager.getInstance().startPreview(holder, isFirstPreview);
                isFirstPreview = false;
                refreshPreview();
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                AW360MediaManager.getInstance().stopPreview(false);
            }
        });

        mSurfaceView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (!isCalibrate && isActivate) {
                    showDisplaySettingDialog();
                }

                return true;
            }
        });
    }

    private void showDisplaySettingDialog() {
        DisplaySetDialog dialog = new DisplaySetDialog(this);
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
    }

    private void addCarView() {
        if (!isActivate) {
            return;
        }
        CarPosition position = null;
        if (isCalibrate) {
            position = AW360API.getInstance().getBirdViewCarPosition();
        } else {
            position = AW360API.getInstance().getMixCarPosition();
        }

        if (mCarView == null) {
            mCarView = new ImageView(this);
            mCarView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    if (isCalibrate) {
                        return false;
                    }
                    mUpLayout.setVisibility(View.VISIBLE);
                    return true;
                }
            });
            mCarView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (isCalibrate) {
                        return;
                    }
                    mUpLayout.setVisibility(View.GONE);
                }
            });
        } else {
            mMainLayout.removeView(mCarView);
        }


        Point point = DisplayUtil.getScreenMetrics(getApplicationContext());

        int screenW = point.x;
        int screenH = point.y;

        float x = position.getX() * screenW / 800;
        float y = position.getY() * screenH / 480;
        int width = position.getWidth() * screenW / 800;
        int height = position.getHeight() * screenH / 480;


        mCarView.setX(x);
        mCarView.setY(y);
        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(width, height);
        mCarView.setLayoutParams(layoutParams);
        mCarView.setImageResource(R.drawable.car);
        mCarView.setScaleType(ImageView.ScaleType.FIT_XY);
        if (isCalibrate || isBirdView) {
            mMainLayout.addView(mCarView);
        }

    }

    private void removeCarView() {
        if (mCarView != null) {
            mMainLayout.removeView(mCarView);
        }
    }


    private void initViewParams() {
        ViewGroup.LayoutParams params = (ViewGroup.LayoutParams) mSurfaceView.getLayoutParams();
        Point p = DisplayUtil.getScreenMetrics(this);
        params.width = p.x;
        params.height = p.y;
        mPreviewRate = DisplayUtil.getScreenRate(this); // 默认全屏的比例预览
        mSurfaceView.setLayoutParams(params);

    }

    private void changeStatus(int isVisible, int resId){
        if(isVisible == View.INVISIBLE){
            mClock.stop();
            red_Point.setVisibility(View.INVISIBLE);
            mRedPointHandler.removeMessages(RED_POINT_VISIBLE);
        }else {
            mClock.start();
            mRedPointHandler.sendEmptyMessageAtTime(RED_POINT_VISIBLE,500);
        }
        mRecordView.setImageResource(resId);
        mClock.setVisibility(isVisible);
    }



    @Override
    public void onClick(View v) {
        if (!isActivate) {
            return;
        }
        switch (v.getId()) {
            case R.id.preview_behind_ib:
                mPreviewDirection = PREVIEW_DIRCETION_BEHIND;
                refreshPreview();
                break;
            case R.id.preview_front_ib:
                mPreviewDirection = PREVIEW_DIRCETION_FRONT;
                refreshPreview();
                break;
            case R.id.preview_left_ib:
                mPreviewDirection = PREVIEW_DIRCETION_LEFT;
                refreshPreview();
                break;
            case R.id.preview_right_ib:
                mPreviewDirection = PREVIEW_DIRCETION_RIGHT;
                refreshPreview();
                break;
            case R.id.preview_model_ib:
                if (isBirdView) {
                    isBirdView = false;
                    mPreviewDirection = PREVIEW_DIRCETION_ALL;
                } else {
                    isBirdView = true;
                    mPreviewDirection = PREVIEW_DIRCETION_FRONT;
                }
                refreshPreview();
                break;
            case R.id.surfaceView:
                doubleClick();

                break;
            case R.id.start_record_ib:
                if (AW360MediaManager.getInstance().isRecording() == false) {
                    AW360MediaManager.getInstance().startRecorder(mHandler);
                }else {
                    AW360MediaManager.getInstance().stopRecorder();
                }
                break;
            case R.id.exit_b:
                if (isCalibrate) {
                    LogUtil.i(TAG,"isCalibrate=true");
                    exitCalibrateMode();
                    refreshPreview();
                } else {
                    LogUtil.i(TAG,"isCalibrate=false");
                    exitApp();
                }
                break;
            case R.id.save_b:
                requestFocus(v);
                hideInputWindow();
                AW360API.getInstance().save();
                break;
            case R.id.calibrate_b:
                hideInputWindow();
                calibrate();
                break;

            case R.id.set_ib:
                AW360MediaManager.getInstance().stopRecorder();
                changeStatus(View.INVISIBLE,R.mipmap.record_start);
                Intent intent = new Intent(this, SettingsActivity.class);
                startActivity(intent);
                break;
            case R.id.files_ib:
                AW360MediaManager.getInstance().stopRecorder();
                changeStatus(View.INVISIBLE,R.mipmap.record_start);
                Intent intentFile = new Intent(this,FileListActivity.class);
                startActivity(intentFile);
                break;
            case R.id.export_b:
                exportData();
                break;
            case R.id.import_b:
                importData();
                break;
            case R.id.zoom_in_ib:
                zoomIn();
                break;
            case R.id.zoom_out_ib:
                zoomOut();
                break;
            case R.id.up_ib:
                moveToUp();
                break;
            case R.id.down_ib:
                moveToDown();
                break;
            case R.id.left_ib:
                moveToLeft();
                break;
            case R.id.right_ib:
                moveToRight();
                break;
            case R.id.exchange_ib:
                AW360API.getInstance().exchangeDisplayView();
                addCarView();
                break;
            case R.id.add_range_ib:
                AW360API.getInstance().setViewRangeFar();
                addCarView();
                break;
            case R.id.sub_range_ib:
                AW360API.getInstance().setViewRangeNear();
                addCarView();
                break;
        }
    }

    private void refreshPreview() {
        if (!isActivate) {
            mPreviewDirection = PREVIEW_DIRCETION_ALL;
            return;
        } else {
            if (mPreviewDirection == -1) {
                mPreviewDirection = PREVIEW_DIRCETION_FRONT;
            }
        }
        if (isBirdView) {
            mModeView.setSelected(false);
            addCarView();
        } else {
            mModeView.setSelected(true);
            removeCarView();
        }
        switch (mPreviewDirection) {
            case PREVIEW_DIRCETION_ALL:
                mFrontView.setSelected(false);
                mRearView.setSelected(false);
                mLeftView.setSelected(false);
                mRightView.setSelected(false);
                if (isBirdView) {
                    AW360API.getInstance().previewBFMode();
                } else {
                    AW360API.getInstance().previewCAMode();
                }
                break;
            case PREVIEW_DIRCETION_FRONT:
                mFrontView.setSelected(true);
                mRearView.setSelected(false);
                mLeftView.setSelected(false);
                mRightView.setSelected(false);
                if (isBirdView) {
                    AW360API.getInstance().previewBFMode();
                } else {
                    AW360API.getInstance().previewCFMode();
                }
                break;
            case PREVIEW_DIRCETION_BEHIND:
                mFrontView.setSelected(false);
                mRearView.setSelected(true);
                mLeftView.setSelected(false);
                mRightView.setSelected(false);
                if (isBirdView) {
                    AW360API.getInstance().previewBBMode();
                } else {
                    AW360API.getInstance().previewCBMode();
                }
                break;
            case PREVIEW_DIRCETION_LEFT:
                mFrontView.setSelected(false);
                mRearView.setSelected(false);
                mLeftView.setSelected(true);
                mRightView.setSelected(false);
                if (isBirdView) {
                    AW360API.getInstance().previewBLMode();
                } else {
                    AW360API.getInstance().previewCLMode();
                }
                break;
            case PREVIEW_DIRCETION_RIGHT:
                mFrontView.setSelected(false);
                mRearView.setSelected(false);
                mLeftView.setSelected(false);
                mRightView.setSelected(true);
                if (isBirdView) {
                    AW360API.getInstance().previewBRMode();
                } else {
                    AW360API.getInstance().previewCRMode();
                }
                break;
        }

    }

    private void doubleClick() {
        // 双击事件响应
        /**
         * arraycopy,拷贝数组
         * src 要拷贝的源数组
         * srcPos 源数组开始拷贝的下标位置
         * dst 目标数组
         * dstPos 开始存放的下标位置
         * length 要拷贝的长度（元素的个数）
         *
         */
        //实现数组的移位操作，点击一次，左移一位，末尾补上当前开机时间（cpu的时间）
        System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
        mHits[mHits.length - 1] = SystemClock.uptimeMillis();
        //双击事件的时间间隔500ms
        if (mHits[0] >= (SystemClock.uptimeMillis() - 500)) {
            //toCalibrateMode();
            if (isCalibrate) {
                return;
            }
            mPasswordView.setVisibility(View.VISIBLE);
        } else {
            if (!isCalibrate) {
                if (mControllerLayout.getVisibility() == View.VISIBLE) {
                    mControllerLayout.setVisibility(View.GONE);
                    mControllerLayout2.setVisibility(View.GONE);
                } else {
                    mControllerLayout.setVisibility(View.VISIBLE);
                    mControllerLayout2.setVisibility(View.VISIBLE);
                }
            }
        }
    }

    @Override
    protected void onStart() {
        LogUtil.i(TAG, "onStart");
        boolean result = AW360MediaManager.getInstance().init(this);
        if (result) {
            initSurfaceView();
            initView();
            addCarView();
            AW360API.getInstance().setBirdViewListener(this);
            checkActivate();
        } else {
            finish();
        }
        super.onStart();
    }

    @Override
    protected void onResume() {
        LogUtil.i(TAG, "onResume");
        super.onResume();
    }

    @Override
    protected void onStop() {
        LogUtil.i(TAG, "onStop");
        super.onStop();
        AW360API.getInstance().setBirdViewListener(null);
        AW360MediaManager.getInstance().stopPreview(false);
    }

    @Override
    protected void onDestroy() {
        LogUtil.i(TAG, "onDestroy");
        super.onDestroy();
    }

    private void exitApp() {
        AW360MediaManager.getInstance().stopRecorder();
        AW360MediaManager.getInstance().stopPreview(true);
        AW360MediaManager.getInstance().release();
        finish();
    }

    /**
     * UI切换到校正模式
     */
    private void toCalibrateMode() {
        if (isCalibrate) {
            return;
        }
        AW360API.getInstance().previewCalibrateMode();
        isCalibrate = true;
        mControllerLayout.setVisibility(View.GONE);
        mControllerLayout2.setVisibility(View.GONE);
        mUpLayout.setVisibility(View.GONE);
        mCalibrateLayout.setVisibility(View.VISIBLE);
        mCalibrateLayout2.setVisibility(View.VISIBLE);
        addCarView();
    }

    private void exitCalibrateMode() {
        AW360API.getInstance().cancelCalibrate();
        hideInputWindow();
        mControllerLayout.setVisibility(View.VISIBLE);
        mControllerLayout2.setVisibility(View.VISIBLE);
        mCalibrateLayout.setVisibility(View.GONE);
        mCalibrateLayout2.setVisibility(View.GONE);
        isCalibrate = false;
        isBirdView = true;
        AW360API.getInstance().previewBFMode();
        addCarView();
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            return;
        }
        switch (v.getId()) {
            case R.id.car_width_et:
                int width = Integer.valueOf(mCarWidthView.getText().toString());
                if (width != AW360API.getInstance().getCarWidth()) {
                    AW360API.getInstance().setCarWidth(width);
                }
                break;
            case R.id.car_height_et:
                int height = Integer.valueOf(mCarHeightView.getText().toString());
                if (height != AW360API.getInstance().getCarHeight()) {
                    AW360API.getInstance().setCarHeight(height);
                }
                break;
            case R.id.car_offset_et:
                int offset = Integer.valueOf(mCarOffsetView.getText().toString());
                if (offset != AW360API.getInstance().getCarSideOffset()) {
                    AW360API.getInstance().setSideOffset(offset);
                }
                break;
        }
    }

    private void hideInputWindow() {
        if (getCurrentFocus() == null) {
            return;
        }
        ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(this.getCurrentFocus()
                .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }

    private void calibrate() {
        requestFocus(mCalibrateButton);
        showProgressDialog("导出数据...");
        AW360API.getInstance().birdviewAdjust();
    }

    private void exportData() {
        //showProgressDialog("导出数据...");
        if (!FileUtils.isFolderExist(AW360SharePreferenceUtil.getImportPath())) {
            showMessage(R.string.path_alert);
            return;
        }


        boolean result = AW360API.getInstance().exportData(AW360SharePreferenceUtil.getImportPath() + APPConfig.CONFIG_FILE_NAME);
        if (result) {
            showMessage(R.string.export_success);
        } else {
            showMessage(R.string.export_failed);
        }
    }

    private void importData() {
        // showProgressDialog("导入数据...");
        if (!FileUtils.isFolderExist(AW360SharePreferenceUtil.getImportPath())) {
            showMessage(R.string.path_alert);
            return;
        }
        boolean reulst = AW360API.getInstance().importData(AW360SharePreferenceUtil.getImportPath() + APPConfig.CONFIG_FILE_NAME);
        if (reulst) {
            //TODO restart app
            showMessage(R.string.import_success);
            exitApp();
        } else {
            showMessage(R.string.import_failed);
        }

    }

    private void showProgressDialog(String message) {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(this, R.style.awProgressDialog);
            mProgressDialog.setCanceledOnTouchOutside(false);
            mProgressDialog.setCancelable(false);

            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        }

        if (!mProgressDialog.isShowing()) {
            mProgressDialog.setMessage(message);
            mProgressDialog.show();
        }
    }

    private void dismissProgressDialog() {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
    }


    @Override
    public void onCalibrateDone() {
        dismissProgressDialog();
    }

    @Override
    public void onExportDone() {
        dismissProgressDialog();
    }

    @Override
    public void onImportDone() {
        dismissProgressDialog();
    }

    private void requestFocus(View view) {
        view.setFocusable(true);
        view.setFocusableInTouchMode(true);
        view.requestFocus();
        view.requestFocusFromTouch();
    }

    private void showActivateDialog() {
        if (mAlertDialog == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage(R.string.activate_info);
            builder.setNegativeButton(R.string.skip, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //TODO this is for test;
                    isActivate = true;
                    dialog.dismiss();
                }
            });
            builder.setPositiveButton(R.string.activate, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    if (AW360API.getInstance().doActivate()) {
                        exitApp();
                    } else {
                        showMessage(R.string.activate_app_alert);
                    }

                }
            });
            mAlertDialog = builder.create();
        }

        if (!mAlertDialog.isShowing()) {
            mAlertDialog.show();
        }
    }

    private void showMessage(int resource) {
        Toast.makeText(BirdViewActivity.this, resource, Toast.LENGTH_SHORT).show();
    }


    private void checkActivate() {
        if (!AW360API.getInstance().getActivationStatus()) {
            showActivateDialog();
        }
    }

    /**
     * 将当前预览视图缩小
     */
    private void zoomIn() {
        if (!isBirdView) {
            return;
        }
        switch (mPreviewDirection) {
            case PREVIEW_DIRCETION_FRONT:
                AW360API.getInstance().zoomInFrontCamera();
                break;
            case PREVIEW_DIRCETION_BEHIND:
                AW360API.getInstance().zoomInRearCamera();
                break;
            case PREVIEW_DIRCETION_LEFT:
                AW360API.getInstance().zoomInLeftCamera();
                break;
            case PREVIEW_DIRCETION_RIGHT:
                AW360API.getInstance().zoomInRightCamera();
                break;
        }
    }

    /**
     * 将当前预览视图放大
     */
    private void zoomOut() {
        if (!isBirdView) {
            return;
        }
        switch (mPreviewDirection) {
            case PREVIEW_DIRCETION_FRONT:
                AW360API.getInstance().zoomOutFrontCamera();
                break;
            case PREVIEW_DIRCETION_BEHIND:
                AW360API.getInstance().zoomOutRearCamera();
                break;
            case PREVIEW_DIRCETION_LEFT:
                AW360API.getInstance().zoomOutLeftCamera();
                break;
            case PREVIEW_DIRCETION_RIGHT:
                AW360API.getInstance().zoomOutRightCamera();
                break;
        }
    }

    /**
     * 将当前预览视图向上移动
     */
    private void moveToUp() {
        if (!isBirdView) {
            return;
        }
        int y = 0;
        switch (mPreviewDirection) {
            case PREVIEW_DIRCETION_FRONT:
                y = AW360API.getInstance().getFrontCameraOffsetY();
                LogUtil.i(TAG, "FrontCameraOffsetY =" + y);
                AW360API.getInstance().setFrontCameraOffsetY(y + 2);
                break;
            case PREVIEW_DIRCETION_BEHIND:
                y = AW360API.getInstance().getRearCameraOffsetY();
                AW360API.getInstance().setRearCameraOffsetY(y + 2);
                break;
            case PREVIEW_DIRCETION_LEFT:
                y = AW360API.getInstance().getLeftCameraOffsetY();
                AW360API.getInstance().setLeftCameraOffsetY(y + 2);
                break;
            case PREVIEW_DIRCETION_RIGHT:
                y = AW360API.getInstance().getRightCameraOffsetY();
                AW360API.getInstance().setRightCameraOffsetY(y + 2);
                break;
        }
    }

    /**
     * 将当前预览视图向下移动
     */
    private void moveToDown() {
        if (!isBirdView) {
            return;
        }
        int y = 0;
        switch (mPreviewDirection) {
            case PREVIEW_DIRCETION_FRONT:
                y = AW360API.getInstance().getFrontCameraOffsetY();
                LogUtil.i(TAG, "FrontCameraOffsetY =" + y);
                AW360API.getInstance().setFrontCameraOffsetY(y - 2);
                break;
            case PREVIEW_DIRCETION_BEHIND:
                y = AW360API.getInstance().getRearCameraOffsetY();
                AW360API.getInstance().setRearCameraOffsetY(y - 2);
                break;
            case PREVIEW_DIRCETION_LEFT:
                y = AW360API.getInstance().getLeftCameraOffsetY();
                AW360API.getInstance().setLeftCameraOffsetY(y - 2);
                break;
            case PREVIEW_DIRCETION_RIGHT:
                y = AW360API.getInstance().getRightCameraOffsetY();
                AW360API.getInstance().setRightCameraOffsetY(y - 2);
                break;
        }
    }

    /**
     * 将当前预览视图向左移动
     */
    private void moveToLeft() {
        if (!isBirdView) {
            return;
        }
        int x = 0;
        switch (mPreviewDirection) {
            case PREVIEW_DIRCETION_FRONT:
                x = AW360API.getInstance().getFrontCameraOffsetX();
                LogUtil.i(TAG, "FrontCameraOffsetX =" + x);
                AW360API.getInstance().setFrontCameraOffsetX(x - 2);
                break;
            case PREVIEW_DIRCETION_BEHIND:
                x = AW360API.getInstance().getRearCameraOffsetX();
                LogUtil.i(TAG, "RearCameraOffsetX =" + x);
                AW360API.getInstance().setRearCameraOffsetX(x - 2);
                break;
            case PREVIEW_DIRCETION_LEFT:
                x = AW360API.getInstance().getLeftCameraOffsetX();
                LogUtil.i(TAG, "LeftCameraOffsetX =" + x);
                AW360API.getInstance().setLeftCameraOffsetX(x - 2);
                break;
            case PREVIEW_DIRCETION_RIGHT:
                x = AW360API.getInstance().getRightCameraOffsetX();
                LogUtil.i(TAG, "RightCameraOffsetX =" + x);
                AW360API.getInstance().setRightCameraOffsetX(x - 2);
                break;
        }
    }

    /**
     * 将当前预览视图向右移动
     */
    private void moveToRight() {
        if (!isBirdView) {
            return;
        }
        int x = 0;
        switch (mPreviewDirection) {
            case PREVIEW_DIRCETION_FRONT:
                x = AW360API.getInstance().getFrontCameraOffsetX();
                LogUtil.i(TAG, "FrontCameraOffsetX =" + x);
                AW360API.getInstance().setFrontCameraOffsetX(x + 2);
                break;
            case PREVIEW_DIRCETION_BEHIND:
                x = AW360API.getInstance().getRearCameraOffsetX();
                AW360API.getInstance().setRearCameraOffsetX(x + 2);
                break;
            case PREVIEW_DIRCETION_LEFT:
                x = AW360API.getInstance().getLeftCameraOffsetX();
                AW360API.getInstance().setLeftCameraOffsetX(x + 2);
                break;
            case PREVIEW_DIRCETION_RIGHT:
                x = AW360API.getInstance().getRightCameraOffsetX();
                AW360API.getInstance().setRightCameraOffsetX(x + 2);
                break;
        }
    }
}
